package ro.dandanciu.webgallery.services.impl;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import ro.dandanciu.webgallery.domainmodel.Advert;
import ro.dandanciu.webgallery.domainmodel.User;
import ro.dandanciu.webgallery.services.AdvertiseServices;
import ro.dandanciu.webgallery.services.email.EmailMessage;
import ro.dandanciu.webgallery.services.email.EmailSender;

@Transactional
public class AdvertiseServicesImpl implements AdvertiseServices{
	private static final String EMAIL_SUBJECT = "[WebGallery] advert for gallery ...";

	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(AdvertiseServicesImpl.class);

	private EntityManager em;

	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}
	
	/**
	 * 
	 * @param advert
	 */
	public void save(Advert advert) {
		if (logger.isDebugEnabled()) {
			logger.debug("save(Advert) - start");
		}

		em.persist(advert);
		
		//send the email
		EmailMessage message = new EmailMessage();
		List<String> userAddresses = new ArrayList<String>();
		for (User user : advert.getUsers()) {
			userAddresses.add(user.getEmail());
		}
		message.setToAddresses(userAddresses );
		message.setSubject(EMAIL_SUBJECT);
		message.setBody(advert.getAText());
		EmailSender.send(message);

		if (logger.isDebugEnabled()) {
			logger.debug("save(Advert) - end");
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Advert> getForUser(User user) {
		if (logger.isDebugEnabled()) {
			logger.debug("getForUser(String) - start");
		}

		Query query = em.createNamedQuery("Advert.findForUser");
		query.setParameter("userId", user.getUserId());
		List<Advert> returnList = query.getResultList();
		if (logger.isDebugEnabled()) {
			logger.debug("getForUser(String) - end");
		}
		return returnList;
	}

}
